#!usr/bin/node

const http = require('http'),
      fs = require('fs');

let items = loadData();

http.createServer((req,res) => {
  console.log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
  console.log(items);
  switch(req.method) {
    case 'GET':
      select(req,res);
      break;
    case 'POST':
      insert(req,res);
      break;
    case 'DELETE':
      del(req,res);
      break;
    case 'PUT':
      update(req,res);
      break;
    default:
      res.end('request method not support!');
  }

}).listen(8080);

process.on('SIGINT',()=>{
  save();
  process.exit(1);
});

process.on('beforeExit',()=>{
  save();
  process.exit(0);
})

function select(req,res) {
  res.setHeader('Access-Control-Allow-Origin','*');
  res.end(JSON.stringify(items));
}

function insert(req,res) {
  res.setHeader('Access-Control-Allow-Origin','*');
  let item = '';
  req.on('data',chunk => {
    item += chunk;
  });
  console.log(item);
  req.on('end',() => {
    item = new URLSearchParams(item);
    item = item.get('item');
    if(item !== '' || typeof item !== 'undefined') {
      item = {
        id:Date.now(),
        value:item
      };
      items.push(item);
      res.end('insert ok!');
    }else {
      res.end('item empty');
    }
  })
}

function del(req,res) {
  res.setHeader('Access-Control-Allow-Origin','*');
  
  let id = '';
  req.on('data',chunk => {
    id += chunk;
  });
  req.on('end',() => {
    id = new URLSearchParams(id);
    id = id.get('id');
    items.filter(item => {
      item.id !== id;
    });
    res.end('delete successfully!');
  });
}

function update(req,res) {
  res.setHeader('Access-Control-Allow-Origin','*');

  let id = '',item = '';
  req.on('data',chunk => {
    id += chunk;
  });
  req.on('end',() => {
    id = new URLSearchParams(id);
    id = id.get('id');
    item = new URLSearchParams(item);
    item = item.get('item');
    items.map(item => {
      if(id === item.id) {
        return {
          id:item.id,
          value:item
        }
      }else {
        return {
          id:item.id,
          value:item.value
        }
      }
    });

    res.end('update successfully!');
  })
}

function loadData() {
  try{
    let data = fs.readFileSync('./data.txt','utf8');
    console.log(data);
    return JSON.parse(data);
  }catch(err){
    return [];
  }
}

function save() {
  try{
    fs.writeFileSync('./data.txt',JSON.stringify(items),'utf8');
  }catch(err){
    console.error(err);
  }
}
